package com.zbs.simbot.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.Map;

@Slf4j
public class HttpUtils extends HttpUtil {
    public static String get(String url,Map<String,Object> param,Map<String,String> headers) {
        return get(url,param, headers, -1);
    }

    public static String get(String url,Map<String,Object> param,Map<String,String> headers,int timeoutSeconds) {
        HttpRequest http = createGet(url);
        return getHttp(param, headers, timeoutSeconds, http);
    }

    public static String postToJson(String url, Map<String, Object> param) {
        return postToJson(url, param, null, -1);
    }

    public static String postToJson(String url, Map<String, Object> param, Map<String, String> headers) {
        return postToJson(url, param, headers, -1);
    }

    public static <T> T postToJsonForObj(String url, Map<String, Object> param) {
        return postToJsonForObj(url, param, null, -1);
    }

    public static <T> T postToJsonForObj(String url, Map<String, Object> param, Map<String, String> headers) {
        return postToJsonForObj(url, param, headers, -1);
    }

    /**
     * JSON http 请求
     * @param url url
     * @param param 参数
     * @param headers 请求头
     * @param timeoutSeconds 超时时间
     * @return String
     */
    public static String postToJson(String url, Map<String, Object> param, Map<String, String> headers,int timeoutSeconds) {
        HttpRequest http = createPost(url);
        return getHttp(param, headers, timeoutSeconds, http);
    }

    /**
     * JSON http 请求
     * @param url url
     * @param param 参数
     * @param headers 请求头
     * @param timeoutSeconds 超时时间
     * @return T
     */
    public static <T> T postToJsonForObj(String url, Map<String, Object> param, Map<String, String> headers,int timeoutSeconds) {
        String body = postToJson(url, param, headers, timeoutSeconds);
        try {
            return JSON.parseObject(body, new TypeReference<T>() {});
        } catch (Exception e) {
            log.error("请求异常，转换实体异常，原返回内容：{}",body,e);
            log.error("请求异常，转换实体异常",e);
        }
        return null;
    }

    private static String getHttp(Map<String, Object> param, Map<String, String> headers, int timeoutSeconds, HttpRequest http) {
        if (!CollectionUtils.isEmpty(headers)) {
            headers.forEach(http::header);
        }
        if (!CollectionUtils.isEmpty(param)) {
            http.body(JSON.toJSONString(param));
        }
        if (timeoutSeconds > 0) {
            http.timeout(timeoutSeconds * 1000);
        }
        return http.execute().body();
    }
}
